<template>
  <div class="emil-summary" :element-loading-text="$t('public.loadingText')" style="height: 600px">
    <contact-summary-solt :loading="cardLoading">
      <template slot="customerSlot">
        <customer-slot
          :customer="customer"
          :custType="custType"
          :currentBusinessObj="currentBusinessObj"
          :isDailog="isDailog"
          :isUnbunding='true'
          @unbundling="unRelation"
          @addCustomer="addCustomer"
          @merged="mergeCustomer"
          @requestUpdateCustInfo="handleRequestUpdateCustInfo"
        >
        </customer-slot>
      </template>
      <template slot="funTabSlot">
        <fun-tab-slot :tabs="tabs" :activeName="tabActiveName" @changeDetailTab="refreshContent">
          <!-- 邮件组件 -->
          <template slot="emailTab">
            <email-container :refreshRight="refreshBusRight" :refresh="refresh" v-if="!loading"></email-container>
          </template>
          <!-- 工单组件 -->
          <template slot="businessTab">
            <guide1 :customer="customer"
                   :custType="custType"
                   :currentBusinessObj="currentBusinessObj"
                   @addCustomer="addCustomer"
                   @merged="mergeCustomer"
                   v-if="!isTargetCustomers"></guide1>
            <business :cacheId="currentBusinessObj.callId"
                      v-if="isTargetCustomers"
                      :reload="refreshBusiness"
                      :busId="busId"
                      link="mail"
                      :cid="customerId"
                      :refresh="refresh"
                      :custInfo="customer"
                      :showHistoryTable="true"
                      @event="businessEvent"></business>
          </template>
          <!-- 客户组件 -->
          <template slot="contactPlanTab">
            <guide1 :customer="customer"
                   :custType="custType"
                   :currentBusinessObj="currentBusinessObj"
                   @addCustomer="addCustomer"
                   @merged="mergeCustomer"
                   v-if="!isTargetCustomers"></guide1>
            <contact-plan v-if="isTargetCustomers" :reload="refreshBusRight" :cid="customerId" :refresh="refresh"></contact-plan>
          </template>
          <!-- 联系历史 -->
          <template slot="historyTab">
            <guide1 :customer="customer"
                   :custType="custType"
                   :currentBusinessObj="currentBusinessObj"
                   @addCustomer="addCustomer"
                   @merged="mergeCustomer"
                   v-if="!isTargetCustomers"></guide1>
            <contact-history v-if="isTargetCustomers" :cid="customerId" :refreshBusRight="refreshBusRight" :refresh="refresh"></contact-history>
          </template>
          <!-- 操作日志 -->
          <template slot="changeLogTab">
            <guide1 :customer="customer"
                   :custType="custType"
                   :currentBusinessObj="currentBusinessObj"
                   @addCustomer="addCustomer"
                   @merged="mergeCustomer"
                   v-if="!isTargetCustomers"></guide1>
            <operation-log v-if="isTargetCustomers" :cid="customerId" :refreshBusRight="refreshBusRight"  :refresh="refresh"></operation-log>
          </template>
        </fun-tab-slot>
      </template>
    </contact-summary-solt>
  </div>
</template>
<script>
  import {isHasMenu} from '@/utils/m7Utils'
  import guide1 from '@/components/public-modules/cust-tab-content/guide/index.vue'
  import ContactSummarySolt from '@/components/public-modules/contact-summary/index.vue'
  import CustomerSlot from '@/components/public-modules/contact-summary/CustomerSlot'
  import FunTabSlot from '@/components/public-modules/contact-summary/FunTab'
  import ContactPlan from '@/components/public-modules/cust-tab-content/contact-plan/'
  import ContactHistory from '@/components/public-modules/cust-tab-content/contact-history/'
  import Business from '@/components/public-modules/cust-tab-content/business/'
  import EmailContainer from './EmailContainer.vue'
  import OperationLog from '@/components/public-modules/cust-tab-content/operation-log/'
  import { isEmpty } from 'lodash'
  import * as globalTypes from 'src/store/mutation-types'

  export default {
    name: 'EmailSummary',
    data () {
      return {
        // tabsInit: {
        //   email: {disabled: false},
        //   businessCreateBeforePlan: {disabled: true},
        //   plan: {disabled: true},
        //   history: {disabled: true},
        //   changeLog: {disabled: false}
        // },
        tabsInit: {
          normalTab: {
            email: {disabled: false, name: 'email', slotName: 'emailTab', labelName: this.$t('public.mail')},
            businessCreateBeforePlan: {disabled: true, name: 'business', slotName: 'businessTab', labelName: this.$t('public.business')},
            plan: {disabled: true, name: 'plan', slotName: 'contactPlanTab', labelName: this.$t('public.contactPlan')}}},
        refresh: 'email',
        tabActiveName: 'email',
        tabType: 'email_todo',
        isDailog: true,
        loading: true,
        cardLoading: false, // 从卡片点击到右边的时候的加载
        customerId: '',
        currentEmail: '',
        refreshBusiness: 0,
        busId: '',
        sessionId: '',
        isTargetCustomers: true
      }
    },
    computed: {
//      fun-tab加载项
      tabs () {
        this.isTargetCustomers = true
        let tabs2 = {
          normalTab: {
            email: {disabled: false, name: 'email', slotName: 'emailTab', labelName: this.$t('public.mail')},
            businessCreateBeforePlan: {disabled: false, name: 'business', slotName: 'businessTab', labelName: this.$t('public.business')},
            plan: {disabled: false, name: 'plan', slotName: 'contactPlanTab', labelName: this.$t('public.contactPlan')}
          }
        }
        if ((this.$store.state.session.user && this.$store.state.session.user.isAdmin) || !this.isHaveMenu('func_contact_history')) {
          tabs2.normalTab.history = {disabled: false, name: 'history', slotName: 'historyTab', labelName: this.$t('public.history')}
        }
        if ((this.$store.state.session.user && this.$store.state.session.user.isAdmin) || !this.isHaveMenu('func_operation_log')) {
          tabs2.normalTab.changeLog = {disabled: false, name: 'changeLog', slotName: 'changeLogTab', labelName: this.$t('public.changeLog')}
        }
        let currentCustomer = this.$store.state.email.current[this.tabType].currentCustomer
        if (isEmpty(currentCustomer)) {
          this.isTargetCustomers = false
        } else {
          this.isTargetCustomers = true
        }
        return tabs2
      },
      currentBusinessObj () {
        // 传递给客户模块的业务信息
        let dealSrc = this.tabType === 'email_todo' ? 'popupEmail' : 'relocationEmail'
        let currSession = this.$store.state.email.current[this.tabType].currentSession
        let callId = currSession._id || ''
        return {dealSrc: dealSrc, callId: callId, tabType: this.tabType, type: 'email'}
      },
//      当前会话的客户信息
      customer () {
        let currCustomer = this.$store.state.email.current[this.tabType].currentCustomer
        this.customerId = currCustomer._id || ''
        let currSession = this.$store.state.email.current[this.tabType].currentSession
        let addr = ''
        if (!isEmpty(currSession)) {
          addr = currSession.from.addr
        }
        return isEmpty(currCustomer) ? {email: [{email: addr, memo: ''}]} : currCustomer
      },
//      客户类型
      custType () {
        let currCustomer = this.$store.state.email.current[this.tabType].currentCustomer
        return isEmpty(currCustomer) ? 'unk' : 'one'
      },
      refreshBusRight () {
        return this.$store.state.email.refreshBusRight || 0
      }
    },
    watch: {
      'refreshBusRight': 'fetchData',
      $route (to, form) {
        if (to.path.split('/')[2] === 'email' && to.path.split('/')[3] && this.cardLoading === false) {
          this.fetchData()
        }
      }
    },
    created () {
      this.fetchData()
    },
    methods: {
      isHaveMenu (func) {
        return isHasMenu(func, this.$store.state.session.user)
      },
//      工单模块自定义事件
      businessEvent (eventData) {
        let data = eventData.data
        this.busId = data._id
        if (eventData.event !== 'changeBusinessMaster') {
          this.$store.dispatch('getBusinessDetailById', {_id: this.busId})
        }
        this.$store.commit('business/REFRESH_CUSTOMER_BUSINESS_HISTORY', this.customerId)
        //刷新新版工单左侧菜单栏数量统计
        this.$store.commit('business/REFRESH_MENUBAR',Math.random())
      },
//      获取数据
      fetchData () {
        this.loading = true
        this.refresh = 'email'
        let path = this.$route.path.split('/')
        let type = path[2]
        this.sessionId = path[4]
        if (type !== 'email' || path.length <= 3) {
          this.cardLoading = false
          return
        }
        this.cardLoading = true
        this.$emit('routeChange', this.tabType)
        let tabType = path[3]
        let _id = path[4]
        this.tabType = tabType
        let fromEmail = ''
        let emailList = this.$store.state.email.emailList[path[3]].list // 加载右侧判断当前会话是否在左侧列表中
        let flag = true
        emailList.forEach((item) => {
          if (item._id === path[4]) {
            flag = false
          }
        })
        if (flag) {
          // this.$router.push({path: '/index/email/'})
          // this.cardLoading = false
          return
        }
        // 翻页后该数据获取不到
        this.$store.state[type][type + 'List'][this.tabType].list.forEach(function (item) {
          if (item._id === _id) {
            fromEmail = item.from.addr
          }
        })
        const f1 = getEmailDetail(this.$store, _id, fromEmail, this.tabType)
        const f2 = getEmailHistory(this.$store, _id, this.tabType)
        let that = this
        return Promise.all([f1, f2]).then((val) => {
          console.log(that.$store.state.email)
          that.loading = false
          that.cardLoading = false
          if (this.tabType === 'email_todo') {
            this.tabActiveName = this.$store.state.email.funTabInfo[_id] || 'email' // 回显funTab
            this.$store.dispatch('refreshLeakNum', {_id: _id})
          } else {
            this.tabActiveName = 'email'
          }
          this.$nextTick(() => {
            // 处理中邮件，记录tab页导致不更新问题
            this.refresh = this.tabActiveName
            if (this.tabActiveName === 'business') {
              this.refreshBusiness = this.refreshBusRight
            }
          })
        })
      },
      handleRequestUpdateCustInfo (done) {
        try {
          var promise = this.fetchData()
          if (!promise) {
            done()
          } else {
            promise.then(() => {
              this.$store.commit(globalTypes.UPDATE_CUSTOMER_INFO, {data: this.customer})
              done()
            })
          }
        } catch (error) {
          done()
        }
      },
//      增加客户
      addCustomer (val) {
        let currentCustomer = val.customerInfo
        delete val.customerInfo
        let currentSession = this.$store.state.email.current[this.tabType].currentSession
        if (!isEmpty(currentSession) && !isEmpty(currentSession.from.addr)) {
          this.$store.dispatch('updateCurrentEmailListCustomer', {addr: currentSession.from.addr, customer: currentCustomer})
        }
      },
//      合并客户
      mergeCustomer (val) {
        let data = {
          customerId: val._id,
          callId: this.$route.params.id,
          custName: val.name,
          customer: val.custInfo,
          submenu: this.tabType,
          sessionId: this.$route.path.split('/')[4]
        }
        return this.$store.dispatch('locationCustomerForEmail', data).then(val2 => {
          this.isDailog = false
          this.$message({
            type: 'success',
            message: this.$t('customer.succMerge')
          })
          let currentSession = this.$store.state.email.current[this.tabType].currentSession
          if (!isEmpty(currentSession) && !isEmpty(currentSession.from.addr)) {
            this.$store.dispatch('updateCurrentEmailListCustomer', {addr: currentSession.from.addr, customer: val.custInfo})
          }
        })
      },
//      刷新客户
      refreshContent (name) {
        this.refresh = name
        this.tabActiveName = name
        this.$store.dispatch('saveEmailFunTabInfo', {sessionId: this.sessionId, funTabActiveName: name}).then(() => {
          this.refresh = name
          this.tabActiveName = name
        })
        if (name === 'business') {
          this.busId = ''
          this.refreshBusiness = this.refreshBusRight
        }
      },
//      解除会话与客户的关联提示框
      unRelation () {
//        let self = this
        this.$confirm(this.$t('public.unlinkCustomerPrompt'), this.$t('public.tip'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        }).then(() => {
          let currentSession = this.$store.state.email.current[this.tabType].currentSession
          if (!isEmpty(currentSession) && !isEmpty(currentSession.from.addr)) {
            let data = {
              customerId: this.customerId,
              email: currentSession.from.addr
            }
            this.$store.dispatch('deleteCustomerImRelationForMail', data)
          }
        }).catch(() => {})
      }
    },
    components: {
      guide1,
      ContactSummarySolt,
      CustomerSlot,
      FunTabSlot,
      Business,
      ContactHistory,
      EmailContainer,
      ContactPlan,
      OperationLog
    }
  }
//  获取邮件详情
  function getEmailDetail (store, _id, fromEmail, submenu) {
    let data = {_id: _id, fromEmail: fromEmail, submenu}
    return store.dispatch('popupEmail', data)
  }
//  获取邮件历史
  function getEmailHistory (store, sessionId, submenu) {
    let data = {sessionId: sessionId, submenu}
    return store.dispatch('loadEmailHistory', data)
  }
</script>
<style lang="stylus" scoped>
  @import "../../../assets/common.styl"
</style>
